﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SqlSugarCoreDemo.DBSqlSugar
{
    public static class SqlSugarSetup
    {
        public static void AddSqlSugarSetup(this IServiceCollection services)
        {
            //注入Sql工作单元
            services.AddScoped<IUnitOfWork, UnitOfWork>();


            //服务为空
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            #region SqlSugarClient配置=======================
            //写入主数据库地址
            string mainConn = "server=127.0.0.1;uid=sqlsugar_user;pwd=sqlsugar_user;database=SqlSugarCoreDemo;";
            //string mainConn = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, "DataBase/SqlSugarDB.db");
            var dbType = DbType.SqlServer;
            //var dbType = DbType.Sqlite;
            #endregion

            //注入SqlSugar：AddSingleton  AddScoped
            services.AddScoped<ISqlSugarClient>(o =>
            {
                #region Sql执行拦截器========================
                var aopEvents = new AopEvents
                {
                    //SQL执行前
                    OnLogExecuting = (sql, pars) =>
                    {
                        //Console.WriteLine(sql);
                        //Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));

                        ////通过TempItems这个变量来算出这个SQL执行时间（1）
                        //if (db.TempItems == null) db.TempItems = new Dictionary<string, object>();
                        //db.TempItems.Add("logTime", DateTime.Now);
                        ////通过TempItems这个变量来算出这个SQL执行时间（2）
                        //var startingTime = db.TempItems["logTime"];
                        //db.TempItems.Remove("time");
                        //var completedTime = DateTime.Now;
                    },
                    //SQL执行完事件
                    OnLogExecuted = (sql, pars) => { },
                    //执行SQL 错误事件
                    OnError = (exp) =>
                    {
                        //List<SugarParameter> pars = null;
                        //try
                        //{
                        //    pars = ((SugarParameter[])exp.Parametres).ToList();
                        //}
                        //catch { }
                        //string message = exp.Message;
                        //if (pars != null)
                        //{
                        //    message += "\r\nSql=" + exp.Sql;
                        //    message += "\r\nParameter=" + string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value));
                        //}
                        //LogHelper.Error(LogHelper.LogType.DataBase, "执行SQL错误事件", message, exp);
                        //throw new Exception(message, exp);

                        Console.WriteLine("SQL执行出错：" + exp.Message);
                    }
                };
                #endregion

                //创建DB象
                var db = new SqlSugarClient(new List<ConnectionConfig>()
                {
                    //主租户
                    new ConnectionConfig()
                    {
                        //主数据库
                        ConfigId = DBTenantIds.Main,
                        ConnectionString = mainConn,
                        //数据库类型
                        DbType = dbType,
                        IsAutoCloseConnection = true,
                        InitKeyType = InitKeyType.Attribute,
                        //Sql执行拦截器
                        AopEvents = aopEvents,
                          //配置扩展服务
                        ConfigureExternalServices = new ConfigureExternalServices()
                        {
                            //实体配置
                            EntityService = (t, column) =>
                            {
                                //默认值设置为空
                                if (dbType == DbType.Sqlite)
                                {
                                    column.DefaultValue = null;
                                }
                            }
                        },
                    }
                });
                return db;
            });

            //注入DB工作单元
            services.AddScoped<IUnitOfWork, UnitOfWork>();
        }
    }
}
